package com.example.dishit.view.createdish;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.dishit.R;
import com.example.dishit.controller.callback.IDishDataCallback;
import com.example.dishit.controller.createdish.CreateDishController;
import com.example.dishit.controller.createdish.ICreateDishController;
import com.example.dishit.controller.main.MainController;
import com.example.dishit.model.dish.DishData;
import com.example.dishit.service.recommendation.FakeRecommendationGenerator;

public class CreateDishActivity extends Activity implements ICreateDishView {
    private ICreateDishController controller;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_dish);
        
        // Create "Create Dish" controller.
        controller = new CreateDishController(this);
        
        // NEARBY RESTAURANTS SPINNER/DROP-DOWN-BOX
        final Activity thisActivity = this;
        controller.getNearbyRestaurants(new IDishDataCallback() {
            public void onDishDataCallback(final List<DishData> result) {
                thisActivity.runOnUiThread(new Runnable() {
                    public void run() { drawRestaurantSpinner(thisActivity, result); }
                });
            }
        });
        
        // TAKE A PICTURE
        final ImageButton takePictureButton = (ImageButton)findViewById(R.id.take_dish_pic_button);
        takePictureButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                controller.takePicture();
            }
        });
    }
    
    private static void drawRestaurantSpinner(final Activity thisActivity, final List<DishData> nearbyRestaurants) {
        final Spinner restaurantNameSpinner = (Spinner)thisActivity.findViewById(R.id.create_dish_restaurant_name);
        final RestaurantArrayAdapter adapter = new RestaurantArrayAdapter(thisActivity, nearbyRestaurants);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        restaurantNameSpinner.setAdapter(adapter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_create_dish, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_button:
                final DishData data = createDish();
                if(data != null) controller.sendDish(data);
                
                return true;
            case R.id.cancel_created_dish_button:
                controller.cancel();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    private DishData createDish() {
        // Make sure a restaurant is selected.
        final Spinner restaurantNameSpinner = (Spinner)findViewById(R.id.create_dish_restaurant_name);
        final DishData selectedRestaurant = (DishData)restaurantNameSpinner.getSelectedItem();
        if(selectedRestaurant == null) {
            Toast.makeText(this, "You must select a restaurant.", Toast.LENGTH_LONG).show();
            return null;
        }
        
        final DishData.Builder builder = new DishData.Builder();
        
        // Move all of the boring stuff over.
        builder.restaurantName(selectedRestaurant.getRestaurantName());
        builder.priceMin(selectedRestaurant.getPriceMin());
        builder.priceMax(selectedRestaurant.getPriceMax());
        builder.imageUrls(selectedRestaurant.getImageUrls());
        builder.keywords(selectedRestaurant.getKeywords());
        builder.mapUrl(selectedRestaurant.getMapUrl());
        builder.streetAddress(selectedRestaurant.getStreetAddress());
        builder.city(selectedRestaurant.getCity());
        builder.state(selectedRestaurant.getState());
        builder.zipcode(selectedRestaurant.getZipcode());
        builder.phoneNumberDigits(selectedRestaurant.getPhoneNumberDigits());
        builder.websiteUrl(selectedRestaurant.getWebsiteUrl());
        
        // RECOMENNDED BY
        builder.recommendedBy(MainController.THIS_USER_ID);
        
        // IMAGE
        final ImageView imageView = (ImageView)findViewById(R.id.create_dish_image);
        final Drawable drawable = imageView.getDrawable();
        if(drawable != null) {
            // Convert Drawable to Bitmap.
            final BitmapDrawable bitMapDrawable = (BitmapDrawable)drawable;
            final Bitmap bitmap = bitMapDrawable.getBitmap();
            
            // Convert Bitmap to byte array.
            final ByteArrayOutputStream out = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG, 100, out);
            try { out.close(); } catch (IOException e) { e.printStackTrace(); }
            final List<byte[]> pngImages = new ArrayList<byte[]>();
            pngImages.add(out.toByteArray());
            
            // Add it to the DishData being constructed.
            builder.pngImages(pngImages);
        }
        
        // RATING
        final RatingBar ratingBar = (RatingBar)findViewById(R.id.create_dish_rating_bar);
        final float rating = ratingBar.getRating();
        if(rating >= 1) {
            builder.rating(rating);
        } else {
            Toast.makeText(this, "You must specify a rating of at least 1 star.", Toast.LENGTH_LONG).show();
            return null;
        }
        
        // COMMENTS
        final EditText commentsEditText = (EditText)findViewById(R.id.comments_edit_text);
        final String comment = commentsEditText.getText().toString();
        final List<String> comments = new ArrayList<String>();
        if(!comment.isEmpty()) {
            comments.add(MainController.THIS_USER_ID + ":    " + comment);
            builder.comments(comments);
        }
        
        // REASONS
        final List<String> reasons = new ArrayList<String>();
        final String reason = MainController.THIS_USER_ID + " Dished It";
        reasons.add(reason);
        builder.reasons(reasons);
        
        // Return a new DishData.
        return builder.build();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            final ImageView imageView = (ImageView)findViewById(R.id.create_dish_image);
            final Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }
    }
}
